package com.tj.jinzao.activity;


import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tj.jinzao.R;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.callback.IUploadView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.model.Target;
import com.tj.jinzao.model.User;
import com.tj.jinzao.presenter.UserPresenter;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.widgets.RoundedImageView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 个人资料页面
 * Created by wjy on 2019/1/5.
 */
public class PersonInfoOtherActivity extends BaseActivity implements IUploadView<List<User>> {

    @BindView(R.id.iv_head)
    RoundedImageView mHeadView;
    @BindView(R.id.et_name)
    TextView mNameView;
    @BindView(R.id.tv_birthday)
    TextView mBirthDayView;
    @BindView(R.id.tv_gender)
    TextView mGenderView;
    @BindView(R.id.et_city)
    TextView mCityView;
    @BindView(R.id.et_intro)
    TextView mIntroView;
    @BindView(R.id.tv_target)
    TextView mTargetView;
    @BindView(R.id.tv_health)
    TextView mHealthView;
    @BindView(R.id.tv_status)
    TextView mStatusView;
    @BindView(R.id.tv_case)
    TextView mCaseView;
    @BindView(R.id.back_lay)
    LinearLayout back_lay;
    @BindView(R.id.tv_label)
    TextView tv_label;
    @BindView(R.id.config)
    TextView config;
    @BindView(R.id.bls_bq)
    RelativeLayout bls_bq;
    private User mUser;


    private UserPresenter mPresenter;
    private void getuser(){
        addSubscription(mApiService.getUserInfoYunXin(id), new SubscriberCallBack<User>(PersonInfoOtherActivity.this) {
            @Override
            protected void onSuccess(User user) {
                mUser=user;
                Glide.with(PersonInfoOtherActivity.this).load(Constant.IMAGE_PREFIX+user.getImgurl()).into(mHeadView);
                mNameView.setText(user.getNickname());
                mBirthDayView.setText(user.getBirthday());
                mGenderView.setText(user.getGender() == 1 ? "男" : "女");
                mCityView.setText(user.getPermanentResidence());
                mIntroView.setText(user.getSignature());
                mTargetView.setText(user.getPersonalGoal());
                mStatusView.setText(user.getPhysicalConditions());
                mHealthView.setText(user.getFamilyHealth());
                tv_label.setText(user.getUserTags());

            }

            @Override
            protected void onFailure(ResultResponse response) {
            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });
    }
    @OnClick(R.id.bls_lay)
    public void bls_lay(){
        Intent to=new Intent();
        to.putExtra("position",1);
        to.putExtra("userId",String.valueOf(mUser.getId()));
        to.setClass(this,MyHealthCaseActivity.class);
        startActivity(to);
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_me_other_detail;
    }
    String id;
    @Override
    protected void setupView() {
        super.setupView();
        id=getIntent().getStringExtra("id");
        getuser();
        mPresenter = new UserPresenter(this);
        bls_bq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent to=new Intent();
                to.putExtra("mStep",7);
                to.putExtra("mType",4);
                to.setClass(PersonInfoOtherActivity.this,CompleteInfoActivity.class);
                startActivityForResult(to,103);

            }
        });
        config.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mUser==null){
                    ToastUtils.showToast(PersonInfoOtherActivity.this,"信息获取失败，请退出重进");
                    return;
                }
                HashMap<String,Object> hashMap=new HashMap<>();
                hashMap.put("uid",mUser.getId());
                hashMap.put("tags",mUser.getUserTags());
                updateInfo(hashMap);
            }
        });

    }
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;


    public void detachView() {
        onUnsubscribe();
    }


    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mPresenter==null){
            return;
        }
        mPresenter.getBLList();

    }
    @OnClick(R.id.back_lay)
    public void backLay(){
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.detachView();
        detachView();
    }
    public void updateInfo(Map<String, Object> map) {
        addSubscription(mApiService.addLable(map), new SubscriberCallBack<String>(PersonInfoOtherActivity.this) {
            @Override
            protected void onSuccess(String user) {
                ToastUtils.showToast(PersonInfoOtherActivity.this,"添加标签成功");
                finish();
            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }

            @Override
            protected void onFailure(ResultResponse response) {
            }
        });
    }

    @Override
    protected int getLeftButtonResId() {
        return R.mipmap.ic_back;
    }

    @Override
    public Activity getContext() {
        return this;
    }

    @Override
    public void onRequestSuccess(List<User> users) {
        ToastUtils.showToast(this, "更新成功");
        finish();
    }

    @Override
    public void onRequestNoData(String message) {

    }

    @Override
    public void onRequestError(String error_message) {

    }

    @Override
    public void onUploadSuccess(String path, String url) {

    }
    private String bls="";

    @Override
    public void onCaseSuccess(List<Target> list) {
        bls="";
        for (int i=0;i<list.size();i++){
            if(i==0){
                bls=bls+list.get(i).getName();
            }else {
                bls=bls+","+list.get(i).getName();
            }
        }
        mCaseView.setText(bls);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case 103:
                    try {
                        String target=data.getStringExtra("contentName");
                        mUser.setUserTags(target);
                        tv_label.setText(target);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    break;
            }
        }
    }

    @Override
    public void onCaseFailed(String msg) {
        mCaseView.setText("暂无病例史");
    }

}
